let accessToken: string | null = null;

export function setAccessToken(token: string | null) {
  accessToken = token;
}

export async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
  const baseUrl = import.meta.env.VITE_API_BASE_URL || "/api";
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    ...(options.headers as Record<string, string> | undefined),
  };
  if (accessToken) {
    headers["Authorization"] = `Bearer ${accessToken}`;
  }

  try {
    const resp = await fetch(`${baseUrl}${path}`, {
      ...options,
      headers,
    });

    const isJson = resp.headers.get("content-type")?.includes("application/json");
    const data = isJson ? await resp.json() : ({} as unknown as T);

    if (!resp.ok) {
      if (resp.status === 401) {
        setAccessToken(null);
        if (typeof window !== 'undefined') {
          window.location.href = '/login';
        }
      }
      const message = (data as any)?.message || resp.statusText;
      throw new Error(message);
    }
    return data as T;
  } catch (error) {
    // Handle network errors specifically
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('网络连接失败，请检查网络连接或联系管理员');
    }
    throw error;
  }
} 